package com.arvin.faceDetect.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.arvin.faceDetect.databinding.ItemRecognizedFaceBinding
import com.arvin.faceDetect.model.RecognizedFace
import java.text.DecimalFormat

class RecognizedFaceAdapter : ListAdapter<RecognizedFace, RecognizedFaceAdapter.ViewHolder>(DiffCallback()) {
    private var imageWidth: Int = 0
    private var imageHeight: Int = 0

    fun updateItemSize(width: Int, height: Int) {
        imageWidth = width
        imageHeight = height
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemRecognizedFaceBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding, imageWidth, imageHeight)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    class ViewHolder(
        private val binding: ItemRecognizedFaceBinding,
        private val imageWidth: Int,
        private val imageHeight: Int
    ) : RecyclerView.ViewHolder(binding.root) {
        private val percentFormat = DecimalFormat("0%")

        fun bind(face: RecognizedFace) {
            // 设置图片尺寸
            binding.ivFace.layoutParams = binding.ivFace.layoutParams.apply {
                width = imageWidth
                height = imageHeight
            }

            // 设置人脸图片
            face.faceBitmap?.let { bitmap ->
                binding.ivFace.setImageBitmap(bitmap)
            } ?: run {
                // 如果没有图片，显示默认图片或占位符
                binding.ivFace.setImageResource(android.R.drawable.ic_menu_camera)
            }
            
            binding.tvName.text = face.name
            binding.tvConfidence.text = percentFormat.format(face.confidence)
        }
    }

    private class DiffCallback : DiffUtil.ItemCallback<RecognizedFace>() {
        override fun areItemsTheSame(oldItem: RecognizedFace, newItem: RecognizedFace): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: RecognizedFace, newItem: RecognizedFace): Boolean {
            return oldItem == newItem
        }
    }
} 